/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package work.thread_eg.concurrent.blockingqueue;

import lombok.SneakyThrows;

import java.util.concurrent.ArrayBlockingQueue;

/**
 *
 * 阻塞队列结合线程实现生产者和消费者问题
 * 对比  ReentrantLockTest03  类的实现
 *
 *
 * @author Sakura Shen
 * @date 2021/9/26
 */
public class ArrayBlockingQueue01 {

    private final int queueSize = 10;
    private final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(queueSize);

    public static void main(String[] args)  {
        ArrayBlockingQueue01 test = new ArrayBlockingQueue01();
        // 生产者进程
        Producer producer = test.new Producer();
        // 消费者进程
        Consumer consumer = test.new Consumer();

        producer.start();
        consumer.start();
    }

    class Consumer extends Thread{
        @SneakyThrows
        @Override
        public void run() {
            consume();
        }

        private void consume() throws InterruptedException {
            while(true) {
//                TimeUnit.SECONDS.sleep(1);
                try {
                    queue.take();
                    System.out.println("从队列取走一个元素，队列剩余"+
                            queue.size()+"个元素");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class Producer extends Thread{
        @SneakyThrows
        @Override
        public void run() {
            produce();
        }

        private void produce() throws InterruptedException {
            while(true) {
//                TimeUnit.SECONDS.sleep(1);
                try {
                    queue.put(1);
                    System.out.println("向队列取中插入一个元素，队列剩余空间："+
                            (queueSize-queue.size()));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
